/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.pc.ui.client.actions;

import static org.opu.pc.ui.client.widgets.TableRenderPublisher.COLUMN_NAMES;
import static org.opu.pc.ui.client.widgets.TableRenderPublisher.TYPES;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import org.opu.pc.services.beans.PublicationBean;
import org.opu.pc.services.beans.PublisherBean;
import org.opu.pc.ui.client.widgets.PropertiesEditPane;
import org.opu.pc.ui.client.widgets.TabelBeanView;
import org.opu.pc.ui.util.GUIUtils;
import org.opu.pc.ui.util.ResourceHandle;

/**
 * 
 * @author yura
 */
public class NewPublication extends PublicationSearch {
    public static final String PUBLICATION_DATE = "date";

	private static final long serialVersionUID = -3157205013053013023L;
	
	private TabelBeanView table;
	private FileChoosePanel fChoose; 

	@Override
	public String getName() {
		return "NewPublication";
	}

    @Override
    protected void appendDate(LinkedHashMap<String, Object> properties) {
        properties.put(PUBLICATION_DATE, (Date)null);
    }

	@Override
	protected void addPropertiesPane(JPanel cp, PropertiesEditPane pane) {
		table = createTable(new ArrayList<PublisherBean>());
		JPanel tablePanel = new JPanel(new BorderLayout());
		tablePanel.add(new JScrollPane(table), BorderLayout.CENTER);
		tablePanel.add(createEastPublisherPanel(table), BorderLayout.EAST);
		
		Box b = Box.createVerticalBox();
		b.add(Box.createVerticalStrut(GUIUtils.DEFAULT_SPACE));
		b.add(inBordePanel(i18n.getSafe("publication.new.properties") + ": ",
                pane, false));
		b.add(Box.createVerticalStrut(GUIUtils.DEFAULT_SPACE));
		b.add(inBordePanel(i18n.getSafe("publication.new.publishers") + ": ",
                tablePanel, true));
		b.add(Box.createVerticalStrut(GUIUtils.DEFAULT_SPACE));
		b.add(inBordePanel(i18n.getSafe("publication.new.file") + ": ",
                fChoose = new FileChoosePanel(), true));

		cp.add(b);
	}
	
	private JPanel inBordePanel(String title, JComponent comp, boolean space){
		JPanel pane1 = new JPanel(new BorderLayout());
		pane1.setBorder(BorderFactory.createTitledBorder(title));
		if (space) {
			comp = GUIUtils.vBorder(GUIUtils.hBorder(comp));
		}
		pane1.add(comp, BorderLayout.CENTER);
		return pane1;
	}

	@Override
	protected int getMinimalDialogWidth() {
		return 600;
	}
	
	@Override
	protected Boolean getAppliedBool(Map<String, Object> prop) {
		Boolean bool = super.getAppliedBool(prop);
		return bool != null ? bool.booleanValue() : false;
	}

	@Override
	protected OkAction getOkAction(JDialog dialog, PropertiesEditPane pane) {
		return new OkAction(pane, dialog) {

			private static final long serialVersionUID = 8463973341685199259L;

			@Override
			public void runAction(ActionEvent e) throws Exception {
				Map<String, Object> prop = pane.getProperties();
				publicationService.createNew(
						new PublicationBean(-1, 
								NewPublication.this.getName(prop),
                                (String)prop.get(PUBLICATION_PUBLICATIONPLACE),
                                (Date)prop.get(PUBLICATION_DATE),
                                (String)prop.get(PUBLICATION_CONFERENCE_VENUE),
                                (Integer)prop.get(PUBLICATION_PAGE_NUMBER_START),
                                (Integer)prop.get(PUBLICATION_PAGE_NUMBER_END),
								NewPublication.this.getAppliedBool(prop)),
//						IOUtils.toByteArray(new FileInputStream(fChoose.file)),
						readTable(table));
			}
		};
	}

	@Override
	protected String getCacelActionName() {
		return "Close";
	}
	
	private List<PublisherBean> readTable(TabelBeanView table){
		List<PublisherBean> publishers = new ArrayList<PublisherBean>();
		Object[][] content = table.getContent();
		
		for (int i = 0; i < content.length; i++) {
			Object[] objects = content[i];
			publishers.add(new PublisherBean(-1, (String)objects[0],
					(String)objects[1], (String)objects[2], 
					(Boolean)objects[3]));
		}
		
		return publishers;
	}

	private TabelBeanView createTable(List<PublisherBean> publishers) {
		Object[][] rowData = new Object[publishers.size()][4];

		int i = 0;
		for (PublisherBean bean : publishers) {
			rowData[i][0] = bean.getName();
			rowData[i][1] = bean.getSecondName();
			rowData[i][2] = bean.getLastName();
			rowData[i][3] = bean.isStudent(); 
		}

		TabelBeanView tbl = new TabelBeanView(rowData, TYPES, COLUMN_NAMES);
		tbl.setEditable(true);
		tbl.setSize(400, 400);
		return tbl;
	}

	private JComponent createEastPublisherPanel(final TabelBeanView table) {
		Box panel = Box.createVerticalBox();
		panel.add(Box.createVerticalGlue());
		panel.add(new JButton(new AbstractAction("+") {

			private static final long serialVersionUID = -9062952304680072253L;

			@Override
			public void actionPerformed(ActionEvent arg0) {
				Object[][] content = table.getContent();
				Object[][] newContent = new Object[content.length + 1][4];
				System.arraycopy(content, 0, newContent, 0, content.length);
				newContent[content.length] = new Object[4];
				newContent[content.length][0] = "";
				newContent[content.length][1] = "";
				newContent[content.length][2] = "";
				newContent[content.length][3] = true;
				table.setContent(COLUMN_NAMES, TYPES, newContent);
			}
		}));
		panel.add(Box.createVerticalStrut(GUIUtils.DEFAULT_SPACE/2));
		panel.add(new JButton(new AbstractAction("-") {

			private static final long serialVersionUID = -4451514479335048649L;

			@Override
			public void actionPerformed(ActionEvent arg0) {
				Object[][] content = table.getContent();
				if (content.length > 0) {
					Object[][] newContent = new Object[content.length - 1][4];
					System.arraycopy(content, 0, newContent, 0,
							content.length - 1);
					table.setContent(COLUMN_NAMES, TYPES, newContent);
				}

			}
		}));
		panel.add(Box.createVerticalStrut(GUIUtils.DEFAULT_SPACE/2));
		return panel;
	}

	class FileChoosePanel extends JPanel {
		
		private static final long serialVersionUID = 8706763798095671715L;
		
		JTextField field = GUIUtils.addActions(new JTextField());
		JButton chooseBtn;
        JButton openBtn;
        JButton processBtn;
		File file;
		
		public FileChoosePanel() {
			super(new BorderLayout());

			field.setEditable(false);
			field.setBackground(Color.WHITE);
			
			chooseBtn = new JButton(new AbstractAction("Chose file",
					ResourceHandle.getIcon("ChoseFile.png")) {

				private static final long serialVersionUID = 7412846733208444431L;

				@Override
				public void actionPerformed(ActionEvent arg0) {
					JFileChooser c = new JFileChooser();
					int rVal = c.showOpenDialog(null);
					if (rVal == JFileChooser.APPROVE_OPTION) {
						file = c.getSelectedFile();
						field.setText(file.getAbsolutePath());
					}
					onActionFinish();
				}
			});
			
			add(field);
			add(chooseBtn, BorderLayout.EAST);
		}
	}
}
